<template>
  <ComWrapper>
    <el-card shadow="never" style="margin-bottom:20px">
      <el-input placeholder="请输入文件名" v-model="filename" />
      <el-button type="primary" @click="handleDownload">导出多级表头</el-button>
    </el-card>

    <el-table
      :data="list"
      border
    >
      <el-table-column align="center" label="Id">
        <template #default="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="Main Information" align="center">
        <el-table-column label="Title">
          <template #default="scope">
            {{ scope.row.title }}
          </template>
        </el-table-column>
        <el-table-column label="Author" align="center">
          <template #default="scope">
            <el-tag>{{ scope.row.author }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Readings" align="center">
          <template #default="scope">
            {{ scope.row.Readings }}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="Date">
        <template #default="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.Date }}</span>
        </template>
      </el-table-column>
    </el-table>

  </ComWrapper>
</template>

<script setup>
import {ref} from 'vue'
import {parseTime} from '@/function/date'

const list = ref([
  {
    id: 1,
    title: 'title--1',
    author: 'xjc',
    readings: 123,
    content: 'this is a content',
    date: '2020-10-2'
  },
  {
    id: 2,
    title: 'title--2',
    author: 'xjc',
    readings: 456,
    content: 'this is a content',
    date: '2020-10-2'
  },
  {
    id: 3,
    title: 'title--3',
    author: 'xjc',
    readings: 789,
    content: 'this is a content',
    date: '2020-10-2'
  }
])
const filename = ref('')
const downloadLoading = ref(false)

function handleDownload() {
  downloadLoading.value = true
  import('@/plugins/excel').then(excel => {
    const multiHeader = [['Id', 'Main Information', '', '', 'Date']]
    const header = ['', 'Title', 'Author', 'Readings', '']
    const filterVal = ['id', 'title', 'author', 'Readings', 'Date']
    const data = formatJson(filterVal, list.value)
    const merges = ['A1:A2', 'B1:D1', 'E1:E2']
    excel.export_json_to_excel({
      multiHeader,
      header,
      merges,
      data
    })
    downloadLoading.value = false
  })
}
function formatJson(filterVal, jsonData) {
  return jsonData.map(v => filterVal.map(j => {
    if (j === 'timestamp') {
      return parseTime(v[j])
    } else {
      return v[j]
    }
  }))
}
</script>